//
//  PayWx.m
//  ProjectPublic
//
//  Created by ac-hu on 2018/7/12.
//  Copyright © 2018年 ac hu. All rights reserved.
//

#import "PayWx.h"

@interface PayWx()<WXApiDelegate>

@property(nonatomic,copy)NSString *appId;
@property(nonatomic,assign)BOOL registerWx;
@property(nonatomic,copy)succeedPay succeedBlock;
@property(nonatomic,copy)failPay faiBlock;

@end

@implementation PayWx
+(instancetype)share{
    static PayWx *payWx;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (payWx == nil) {
            payWx = [[PayWx alloc]init];
            [payWx configuration];
        }
    });
    return payWx;
}

-(void)configuration{
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Info" ofType:@"plist"];
    NSDictionary * dict = [[NSDictionary alloc] initWithContentsOfFile:path];
    NSArray * URLTypes = dict[@"CFBundleURLTypes"];
    
    for (NSDictionary * dic in URLTypes) {
        if ([[dic objectForKey:@"CFBundleURLName"] isEqualToString:@"weixin"]) {
            NSArray * URLSchemes= [dic objectForKey:@"CFBundleURLSchemes"];
            self.appId = URLSchemes.firstObject;
            break;
        }
    }
    
    self.registerWx = [WXApi registerApp:self.appId];
    if (self.registerWx) {
        NSLog(@"注册成功");
    }else{
        NSLog(@"注册失败");
    }
}

-(void)payOrder:(id)order succeed:(succeedPay)succeed fail:(failPay)fail{
    if (!self.registerWx) {
        fail(@"注册失败");
        return;
    }
    if (![order isKindOfClass:[NSDictionary class]]) {
        fail(@"参数为空");
        return;
    }
    self.succeedBlock = succeed;
    self.faiBlock = fail;
    PayReq *req = [[PayReq alloc]init];
    //由用户微信号和AppID组成的唯一标识，用于校验微信用户
    [req setValuesForKeysWithDictionary:order];
//    NSString * stamp = @"";
//    req.timeStamp = stamp.intValue;
    [WXApi sendReq:req];
}

-(void) onResp:(BaseResp*)resp
{
    //启动微信支付的response
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果，实际支付结果需要去微信服务器端查询
        switch (resp.errCode) {
            case 0:
                if (self.succeedBlock) {
                    self.succeedBlock(@"支付结果：成功！");
                }
                break;
            case -1:
                if (self.faiBlock) {
                    self.faiBlock(@"支付结果：失败！");
                }
                break;
            case -2:
                if (self.faiBlock) {
                    self.faiBlock(@"用户已经退出支付！");
                }
                break;
            default:
                if (self.faiBlock) {
                    self.faiBlock([NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr]);
                }
                break;
        }
    }
}

-(void)monitorResult:(NSURL *)url{
    [WXApi handleOpenURL:url delegate:self];
}
@end
